const fw = require('../../framework.js');
/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 
const uploadFile = function (filePath, dir, successc, failc) {
  if (!filePath || filePath.length < 9) {
    wx.showModal({
      title: '文件错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  fw.getAliToken(function(resToken){
    const aliyunFileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150);

    
    wx.uploadFile({
      url: fw.config.PARAM.ALI_UPLOAD_BASE_URL,//开发者服务器 url
      filePath: filePath,//要上传文件资源的路径
      name: 'file',//必须填file
      formData: {
        'key': aliyunFileKey,
        'policy': resToken.policyBase64,
        'OSSAccessKeyId': resToken.accessKeyId,
        'signature': resToken.signature,
        'success_action_status': '200',
      },
      success: function (res) {
        console.log('upload ali ,res is:',res);
        if (res.statusCode != 200) {
          failc(new Error('上传错误:' + JSON.stringify(res)))
          return;
        }
        successc(fw.config.PARAM.ALI_UPLOAD_BASE_URL + aliyunFileKey);
      },
      fail: function (err) {
        err.wxaddinfo = fw.config.PARAM.ALI_UPLOAD_BASE_URL;
        failc(err);
      },
    })
  });
}


module.exports = uploadFile;